#include <ESP8266WiFi.h>
#include <PubSubClient.h>

#define R_Pin D3
#define G_Pin D4
#define B_Pin D5

// Update these with values suitable for your network.
const char* ssid = "602iot";
const char* password = "18wulian";
const char* mqtt_server = "192.144.231.242";

WiFiClient espClient;
PubSubClient client(espClient);
int value = 0;

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String payload_str = "" ;
  for (int i = 0; i < length; i++) {
    payload_str = payload_str + (char)payload[i];
  }
  Serial.println(payload_str);
  if (payload_str == "LedRedOn") {
    digitalWrite(R_Pin, HIGH);
  } else if (payload_str == "LedRedOff") {
    digitalWrite(R_Pin, LOW);
  } else if (payload_str == "LedGreenOn") {
    digitalWrite(G_Pin, HIGH);
  } else if (payload_str == "LedGreenOff") {
    digitalWrite(G_Pin, LOW);
  } else if (payload_str == "LedBlueOn") {
    digitalWrite(B_Pin, HIGH);
  } else if (payload_str == "LedBlueOff")
    digitalWrite(B_Pin, LOW);
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      client.subscribe("2018A14102/HW");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(R_Pin, OUTPUT);
  pinMode(G_Pin, OUTPUT);
  pinMode(B_Pin, OUTPUT);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}
